// 编写Store


import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const foodsStore = createSlice({
    name: "foods",
    initialState: {
        // 商品列表
        foodsList: [],
        // 菜单激活下标值
        activeIndex:0,
    },
    reducers: {
        // 都是同步方法

        // 更改商品列表
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        // 更改activeIndex
        changeActiveIndex(state,action){
            state.activeIndex=action.payload
        }
    }
})

const {setFoodsList,changeActiveIndex} = foodsStore.actions;
// 异步action
const fetchFoodsList = () => {
    return async (dispatch) => {
        // 编写异步逻辑
        const res =await axios.get("http://localhost:3004/takeaway");
        // 调用dispatch函数提交action
        dispatch(setFoodsList(res.data))
    }
}
// 导出所有action
export {fetchFoodsList,changeActiveIndex}
// 导出reducer
const reducer = foodsStore.reducer
export default reducer